# -*- coding: utf-8 -*-
"""
Created on Mon May 31 03:19:47 2021

@author: wyx
"""

import random

def random_services(items_id, constrains):
    random.seed(1)
    def mask_to_codes(mask):
        binary = '{:0>10}'.format(bin(mask)[2:])
        return set(filter(lambda x: binary[-1-x] == '1', range(10)))
    
    # 生成服务的功能属性
    service_code_dict = {}
    for i in range(1000):
        service_code_dict[i] = mask_to_codes(random.randint(1, 2**len(items_id)-1))
    # 检查是否合理
    check = set()
    flag = 0
    for i in range(1000):
        check |= service_code_dict[i]
        if check == set(range(len(items_id))):
            flag = 1
            break
    if flag == 0:
        assert False
        
    # 生成非功能属性
    service_qos_dict = {}
    for i in range(1000):
        num = len(service_code_dict[i])
        price = random.uniform(10, 100)
        time = random.uniform(10, 50)
        service_qos_dict[i] = (price*num, time)
    
    qos_needed = constrains.copy()
    
    code_service_dict = {}
    for i in range(1000):
        for v in service_code_dict[i]:
            if v not in code_service_dict:
                code_service_dict[v] = []
            code_service_dict[v].append(i)
    
    return code_service_dict, service_code_dict, qos_needed, service_qos_dict

def normalize(qos_needed, service_qos_dict):
    for key in service_qos_dict:
        norm = []
        for i in range(len(qos_needed)):
            norm.append(service_qos_dict[key][i] / qos_needed[i])
        service_qos_dict[key] = tuple(norm)
    for i in range(len(qos_needed)):
        qos_needed[i] = 1

def preprocess(items_id, constraints):
    # service discovery
    code_service_dict, service_code_dict, qos_needed, service_qos_dict = random_services(items_id, constraints)
    # normalize
    normalize(qos_needed, service_qos_dict)
    # return
    return [code_service_dict, service_code_dict, qos_needed, service_qos_dict]
